//
//  DrawingBoard.swift
//  MyPainter
//
//  Created by Yinyin Zeng on 24/5/20.
//  Copyright © 2020 MaoYeYeDeJiangCuCha. All rights reserved.
//

import UIKit
//画板
class DrawingBoard: UIView {


    private let slider = UISlider()
    private var currentValue:Float = 5
    private var NewBezierPathArr :[NewBezierPath] = []
    private let grayBtn = UIButton()
    private let brownBtn = UIButton()
    private let cyanBtn = UIButton()
    private var currentColor = UIColor(cgColor: UIColor.black.cgColor)
    
    private let toolBar = UIToolbar.init(frame: CGRect(x: 0, y: 44, width: UIScreen.main.bounds.size.width, height: 44))
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.backgroundColor = .white
        //顶部视图
        
        toolBar.barTintColor = .white
        let clearScreenBtn = UIBarButtonItem(title: "清屏", style: .plain, target: self, action: #selector(clearScreenAction))
        let fallBackBtn = UIBarButtonItem(title: "回退", style: .plain, target: self, action: #selector(fallBackAction))
        let eraserBtn = UIBarButtonItem(title: "橡皮擦", style: .plain, target: self, action: #selector(eraserAction))
        //创建间隔项
        let flexibleSpaceBtn = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
        let saveBtn = UIBarButtonItem(title: "保存", style: .plain, target: self, action: #selector(saveAction))
        toolBar.setItems([clearScreenBtn,fallBackBtn,eraserBtn,flexibleSpaceBtn,saveBtn], animated: false)
        self.addSubview(toolBar)
        
        
        //底部视图
        let bottom = UIView(frame: CGRect(x: 0, y: self.bounds.height - 150, width: self.bounds.width,height: 150))
        bottom.backgroundColor = .orange
        self.addSubview(bottom)
        //进度条
        slider.frame = CGRect(x: 0, y: 0, width: self.bounds.width, height: 40)
        slider.maximumValue = 30
        slider.minimumValue = 5
        slider.addTarget(self, action: #selector(sliderAction), for: .valueChanged)
        bottom.addSubview(slider)
        //颜色按钮
        grayBtn.backgroundColor = .lightGray
        grayBtn.frame = CGRect(x: 10, y: 60, width: (self.bounds.width - 40)/3, height: 40)
        grayBtn.addTarget(self, action: #selector(grayBtnAction), for: .touchUpInside)
        
        cyanBtn.backgroundColor = .cyan
        cyanBtn.frame = CGRect(x: (self.bounds.width - 40)/3 + 20, y: 60, width: (self.bounds.width - 30)/3, height: 40)
        cyanBtn.addTarget(self, action: #selector(cyanBtnAction), for: .touchUpInside)
        
        brownBtn.backgroundColor = .black
        brownBtn.frame = CGRect(x: 2*(self.bounds.width - 40)/3 + 30, y: 60, width: (self.bounds.width - 30)/3, height: 40)
        brownBtn.addTarget(self, action: #selector(brownBtnAction), for: .touchUpInside)
        
        bottom.addSubview(grayBtn)
        bottom.addSubview(cyanBtn)
        bottom.addSubview(brownBtn)
        
        
        
    }
    
    @objc func grayBtnAction(sender:UIButton){
        if let color = grayBtn.backgroundColor{
            self.currentColor = color
        }
    }
    
    @objc func cyanBtnAction(sender:UIButton){
        if let color = cyanBtn.backgroundColor{
            self.currentColor = color
        }
    }
    
    @objc func brownBtnAction(sender:UIButton){
        if let color = brownBtn.backgroundColor{
            self.currentColor = color
        }
    }
    
    @objc func sliderAction(sender:UISlider){
        self.currentValue = sender.value
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        for touch in touches {
            let locationPoint = touch.location(in: touch.view)
            let bezierPath = NewBezierPath()
            bezierPath.lineWidth = CGFloat(self.currentValue)
            bezierPath.lineColor = self.currentColor
            bezierPath.move(to: locationPoint)
            //把每一次新创建的路径 添加到数组里
            NewBezierPathArr.append(bezierPath)
        }
    }
    
    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        for touch in touches {
            let locationPoint = touch.location(in: touch.view)
            if let NewBezierPath = NewBezierPathArr.last{
                
                 NewBezierPath.addLine(to: locationPoint)
            }
        }
        self.setNeedsDisplay()
    }
    
    
    
    @objc func saveAction(){
        
        self.toolBar.alpha = 0
        
        //开启图形上下文
        UIGraphicsBeginImageContextWithOptions(CGSize(width: self.bounds.width, height: self.bounds.height - 194), false, 0)
        //上下文
        let ctx = UIGraphicsGetCurrentContext()
        //截图
        self.layer.render(in: ctx!)
        //取图片
        let image = UIGraphicsGetImageFromCurrentImageContext()
        //保存到相册
        UIImageWriteToSavedPhotosAlbum(image!, self, #selector(saveImage(image:didFinishSavingWithError:contextInfo:)), nil)
        //关闭图形上下文
        UIGraphicsEndImageContext()
        
    }
    
    @objc private func saveImage(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: AnyObject) {

        self.saveBlock()
    }

    @objc func saveBlock(){
        self.toolBar.alpha = 1
    }
    
    @objc func eraserAction(){
        self.currentColor = self.backgroundColor!
    }
    
    @objc func fallBackAction(){
        self.NewBezierPathArr.removeLast()
        self.setNeedsDisplay()
    }
    
    @objc func clearScreenAction(){
        self.NewBezierPathArr.removeAll()
        self.setNeedsDisplay()
    }
    
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
        //渲染需要在这
        for NewBezierPath in NewBezierPathArr {
            NewBezierPath.lineJoinStyle = .round
            NewBezierPath.lineCapStyle = .round
            NewBezierPath.lineColor.set()
            NewBezierPath.stroke()
        }
    }

}
